using Dapper;
using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;
using Npgsql;

namespace Eno.Infrastructure.InfRepositories;

public class PermissionRepository : IPermissionRepository<AppPermission>
{
    public readonly string _connectionString;

    public PermissionRepository(string connectionString)
    {
        _connectionString = connectionString;
    }
    public async Task<int> AdditionPermissionAsync(AppPermission entity)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"insert into app_permissions(""ID"",""PermissionName"",""IsActived"",""IsDeleted"",""CreatedAt"",""UpdatedAt"") values( @ID,@PermissionName,@IsActived,@IsDeleted,@CreatedAt,@UpdatedAt)";
        return await conn.ExecuteAsync(sql, entity);
    }

    public async Task<int> DeletePermissionAsync(Guid guid)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"delete from app_permissions where ""ID""= @ID ";
        return await conn.ExecuteAsync(sql, new { ID = guid });
    }

    public async Task<IEnumerable<AppPermission>> GetAppPermissionAsync()
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"select * from app_permissions";
        return await conn.QueryAsync<AppPermission>(sql);
    }

    public async Task<AppPermission?> GetPermissionByIDAsync(Guid guid)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"select * from app_permissions where ""ID""= @ID ";
        return await conn.QueryFirstOrDefaultAsync<AppPermission>(sql, new { ID = guid });

    }

    public async Task<int> UpdatePermissionAsync(AppPermission entity)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"update app_permissions set ""PermissionName""= @PermissionName where ""ID""= @ID ";
        return await conn.ExecuteAsync(sql, entity);
    }

    public async Task<IEnumerable<AppRole>> GetRolesByPermissionIdAsync(Guid permissionId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"
        SELECT r.* FROM app_roles r
        INNER JOIN app_roles_permissions rp ON r.""ID"" = rp.""RolesID"" WHERE rp.""PermissionsID"" = @PermissionId";
        return await conn.QueryAsync<AppRole>(sql, new { PermissionId = permissionId });
    }
}